import axios from 'axios'

export const USER_LOGIN_SUCCESS = 'USER_LOGIN_SUCCESS'
export const USER_LOGIN_FAIL = 'USER_LOGIN_FAIL'

interface UserLoginSuccessActionType {
	type: typeof USER_LOGIN_SUCCESS,
	payload: any
}

interface UserLoginFailActionType {
	type: typeof USER_LOGIN_FAIL,
	payload: any
}


export type ActionType = UserLoginSuccessActionType | UserLoginFailActionType

export function userLoginCreateAction(data: { user: string, pwd: string }) {
	return async (dispatch) => {
		const resp = await axios.post('/api/login', data);
		const { code, message } = resp.data

		if (code === 200) {
			const { data } = resp.data
			dispatch(userLoginSuccessCreateAction(data))
		} else {
			dispatch(userLoginFailCreateAction(message))
		}
	}
}

export function userLoginSuccessCreateAction(payload): UserLoginSuccessActionType {
	return { type: USER_LOGIN_SUCCESS, payload }
}

export function userLoginFailCreateAction(payload): UserLoginFailActionType {
	return { type: USER_LOGIN_FAIL, payload }
}